/**
 * @file 工单操作-退款
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.extend({
    list_modify_common: "work/modify/common/zmn.list.modify.common",
}).define(['layer', 'list_modify_common', 'form', 'table', 'zmnUtils', '$http', 'clipboard', 'NP'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var config = layui.oms_work_config;
    var opCommonUtils = layui.list_modify_common;
    let table = layui.table;

    var zmnUtils = layui.zmnUtils;
    var $http = layui.$http;
    var clipboard = layui.clipboard;
    var NP = layui.NP;

    var SAVE_REFUND_URL = '/work/modify/save/refund.action';
    var UPDATE_REFUND_URL = '/work/modify/update/refund.action';
    var MASTER_LIST_URL = '/staff/find/master/list.action';

    // 修改页面弹框是否打开过
    var UPDATE_PAGE_IS_OPEN = false;

    /**
     * 判断是否是正整数且最多小数点后两位;
     * @param val {number/string} 字符串或数字
     * @returns {boolean} 返回是否是数字
     */
    function isNumber(val) {
        var reg = /^(\-|\+)?\d+([.]{1}\d{1,2})?$/;//正负整数到小数点后两位
        return reg.test(val);
    }

    /**
     * 验证
     */
    function defineVerify(){
        form.verify({
            amount: function (val) {
                if(val > 1000000 || val < 0){
                    return "范围在零到一百万之间";
                }
                if(!isNumber(val)){
                    return "金额不合规范";
                }
            },
            content: function (val) {

            }
        })
    }

    /**
     * 渲染工程师选择下拉框
     * @param data 下拉框数据
     */
    function renderMasterSelect(data) {
        var htmlStr = '<option value=""></option>';

        $.each(data, function (index, item) {
            htmlStr += '<option value="' + item.value + '">' + item.text + '-' + item.ext1 + '</option>';
        });

        $('#masterId').html(htmlStr);
        form.render('select');
    }

    // 师傅信息
    let colsMaster = function () { //工程师算账;如果没有工程师提留金额 计算提留金额
        let arr = [];
        let masterList = refundVO.masterList;
        $.each(masterList, function (index, master) {
            let title = master.type === 1 ? '主工程师' : '从工程师';
            let col = {
                field: 'master-' + master.value,
                title: title,
                templet: function (d) {
                    return master.text;
                }
            };
            arr.push(col);
        });
        return [arr];
    }();

    // 师傅信息
    let masterInfo = function () { //工程师算账;如果没有工程师提留金额 计算提留金额
        let arr = [];
        return [arr];
    }();

    /**
     * 初始化页面
     */
    function initPage () {
        //验证
        defineVerify();

        // 初始化剪切板控制器
        clipboard.init();

        // 初始化师傅列表
        table.render({
            elem: '#masters',
            cols: colsMaster,
            data: [masterInfo],
        });

        let refundType = $('input[name="refundType"]:checked').val();
        if (refundVO.refundType) {
            refundType = refundVO.refundType+'';
            $(":radio[name='refundType'][value='" + refundVO.refundType + "']").click();
            $(":radio[name='payTargetChannelId'][value='" + refundVO.payTargetChannelId + "']").click();
            form.render(); //重新渲染显示效果
        }
        changeRefundType(refundType)
    }
    
    function normalizeRefundParams(data) {
        switch (data.payTargetChannelId) {
            case "1" :
                data.payeeThirdAccount = $('#alipayInfo input[name="payeeThirdAccount"]').val();
                data.payeeThirdAccountName = $('#alipayInfo input[name="payeeThirdAccountName"]').val();
                data.payeeThirdAccountBank = '';
                break;
            case "2" :
                data.payeeThirdAccount = $('#weixinInfo input[name="payeeThirdAccount"]').val();
                data.payeeThirdAccountName = $('#weixinInfo input[name="payeeThirdAccountName"]').val();
                data.payeeThirdAccountBank = '';
                break;
            case "5" :
                let payeeThirdAccount = $('#bankInfo input[name="payeeThirdAccount"]').val();
                data.payeeThirdAccount = payeeThirdAccount.replaceAll(" ", "");
                data.payeeThirdAccountName = $('#bankInfo input[name="payeeThirdAccountName"]').val();
                data.payeeThirdAccountBank = $('#bankInfo input[name="payeeThirdAccountBank"]').val();
                break;
            case "31" :
                data.payeeThirdAccount = '';
                data.payeeThirdAccountName = '';
                data.payeeThirdAccountBank = '';
                break;
            case "0" :
                data.payeeThirdAccount = '';
                data.payeeThirdAccountName = '';
                data.payeeThirdAccountBank = '';
                break;
        }
    }

    function normalizeParams (data) {
        data.refundAmount = zmnUtils.unit.YuanToFen(+data.refundAmount);
        normalizeRefundParams(data);
        return data;
    }

    function saveRefund (params, elem) {
        var url = '';
        if (isUpdate) {
            url = UPDATE_REFUND_URL;
        }else {
            url = SAVE_REFUND_URL;
        }
        $http.lockSave(url, params, elem).then(function (data) {
            zmnUtils.layui.toastSuccess('操作成功', function () {
                opCommonUtils.goSomeWorkDetail(data);
            });
        }, function (msg) {
            zmnUtils.layui.toastError(msg || '操作失败');
        });
    }

    // 退款html改变
    function refundHtmlChange() {
        let payTargetChannelId = $('input[name="payTargetChannelId"]:checked').val();
        let payeeThirdAccount = '--';
        switch (payTargetChannelId) {
            case "1" :
                $('#refund_type_text').html('支付宝退款&nbsp;&nbsp;&nbsp;');
                payeeThirdAccount = $('#alipayInfo input[name="payeeThirdAccount"]').val();
                break;
            case "2" :
                $('#refund_type_text').html('微信退款&nbsp;&nbsp;&nbsp;');
                payeeThirdAccount = $('#weixinInfo input[name="payeeThirdAccount"]').val();
                break;
            case "5" :
                $('#refund_type_text').html('银行卡退款&nbsp;&nbsp;&nbsp;');
                payeeThirdAccount = $('#bankInfo input[name="payeeThirdAccount"]').val();
                break;
            case "31" :
                $('#refund_type_text').html('现金退款&nbsp;&nbsp;&nbsp;');
                break;
            case "0" :
                $('#refund_type_text').html('原路退款&nbsp;&nbsp;&nbsp;');
                payeeThirdAccount = payerThirdAccount || '--';
                break;

        }
        $('#payee_account_text').html(payeeThirdAccount);
    }

    // 校验退款信息
    function verifyRefundInfo() {
        let refundType = $('input[name="refundType"]:checked').val();
        if (!refundType) {
            layer.msg('请选择退款方式');
            return false;
        }
        let refundPath = $('input[name="payTargetChannelId"]:checked').val();
        if (refundType == 2 && !refundPath) {
            layer.msg('请选择退款路径');
            return false;
        }
        let payeeThirdAccount;
        let payeeThirdAccountName;
        let payeeThirdAccountBank;
        let payTargetChannelId = $('input[name="payTargetChannelId"]:checked').val();
        switch (payTargetChannelId) {
            case "1" :
                payeeThirdAccount = $('#alipayInfo input[name="payeeThirdAccount"]').val();
                payeeThirdAccountName = $('#alipayInfo input[name="payeeThirdAccountName"]').val();
                if (!payeeThirdAccount || !payeeThirdAccountName) {
                    layer.msg('请填写账户信息');
                    return false;
                }
                break;
            case "2" :
                payeeThirdAccount = $('#weixinInfo input[name="payeeThirdAccount"]').val();
                payeeThirdAccountName = $('#weixinInfo input[name="payeeThirdAccountName"]').val();
                if (!payeeThirdAccount || !payeeThirdAccountName) {
                    layer.msg('请填写账户信息');
                    return false;
                }
                break;
            case "5" :
                payeeThirdAccount = $('#bankInfo input[name="payeeThirdAccount"]').val();
                payeeThirdAccount = payeeThirdAccount.replaceAll(" ", "");
                payeeThirdAccountName = $('#bankInfo input[name="payeeThirdAccountName"]').val();
                payeeThirdAccountBank = $('#bankInfo input[name="payeeThirdAccountBank"]').val();
                if (!payeeThirdAccount || !payeeThirdAccountName || !payeeThirdAccountBank) {
                    layer.msg('请填写账户信息');
                    return false;
                }

                var regPos = /^\d+(\d+)?$/; //非负浮点数
                if (!regPos.test(payeeThirdAccount)) {
                    layer.msg('银行卡号只能填写数字');
                    return false;
                }
                break;
        }
        return true;
    }

    function getMapName(mapId) {
        for (var i = 0; i < refundReasonList.length; i++) {
            var reasonListElement = refundReasonList[i];
            if (reasonListElement.value.toString() === mapId) {
                return reasonListElement.text;
            }
        }
    }

    function chageRefundPathOpenHtml(refundPath) {
        if (refundPath) {
            // 切换显示内容
            switch (refundPath) {
                case '1':
                    $('#alipayInfo').show();
                    $('#weixinInfo').hide();
                    $('#bankInfo').hide();
                    $('#cashInfo').hide();
                    $('#onlineRefundInfo').hide();
                    break;
                case '2':
                    $('#weixinInfo').show();
                    $('#alipayInfo').hide();
                    $('#bankInfo').hide();
                    $('#cashInfo').hide();
                    $('#onlineRefundInfo').hide();
                    break;
                case '5':
                    $('#bankInfo').show();
                    $('#alipayInfo').hide();
                    $('#weixinInfo').hide();
                    $('#cashInfo').hide();
                    $('#onlineRefundInfo').hide();
                    break;
                case '31':
                    $('#cashInfo').show();
                    $('#bankInfo').hide();
                    $('#alipayInfo').hide();
                    $('#weixinInfo').hide();
                    $('#onlineRefundInfo').hide();
                    break;
                case '0':
                    $('#onlineRefundInfo').show();
                    $('#cashInfo').hide();
                    $('#bankInfo').hide();
                    $('#alipayInfo').hide();
                    $('#weixinInfo').hide();
                    break;
            }
        }else {
            $('#alipayInfo').hide();
            $('#weixinInfo').hide();
            $('#bankInfo').hide();
            $('#cashInfo').hide();
            $('#onlineRefundInfo').hide();
        }

    }

    function chageRefundTypeOpenHtml(refundType) {
        switch (refundType) {
            case '1':
                $('#online_refund_path').show();
                $('#online_refund_amount').show();
                $('#offline_refund_path').hide();
                $('#offline_refund_amount').hide();
                $('#offline_refund_account').hide();
                break;
            case '2':
                $('#online_refund_path').hide();
                $('#online_refund_amount').hide();
                $('#offline_refund_path').show();
                $('#offline_refund_amount').show();
                $('#offline_refund_account').show();
        }
    }

    function changeRefundType(val){
        // 清空退款路径
        var isDelete = true;
        let payTargetChannelId = $('input[name="payTargetChannelId"]:checked').val();
        if (val == 1) {
            if (payTargetChannelId == 0) {
                isDelete = false;
            }
        }else if(val == 2){
            if (payTargetChannelId != 0) {
                isDelete = false;
            }
        }
        if (isDelete) {
            $('input[name=payTargetChannelId]').prop('checked', false);
            form.render('radio');
        }

        chageRefundTypeOpenHtml(val);
        chageRefundPathOpenHtml($('input[name="payTargetChannelId"]:checked').val());

        form.render('input');
    }

    /**
     * 初始化页面事件
     */
    function initEvent () {
        // 监听表单提交
        form.on("submit()",function (obj) {
            var formData = obj.field;

            if (!verifyRefundInfo()) {
                return false;
            }

            let refundType = $('input[name="refundType"]:checked').val();

            switch (refundType) {
                case '1':
                    formData['payTargetChannelId'] = 0;
                    formData['refundAmount'] = $('#online_amount').val();
                    break;
                case '2':
                    formData['refundAmount'] = $('#offline_amount').val();
                    break
            }
            var reasonList = [];
            var formDataArr = $(obj.form).serializeArray();
            for (var i = 0; i < formDataArr.length; i++) {
                var formDatum = formDataArr[i];
                if (formDatum.name === 'reason') {
                    var OrderRemarkDetailDTO = {
                        value: formDatum.value,
                        text: getMapName(formDatum.value)
                    };
                    reasonList.push(OrderRemarkDetailDTO);
                }
            }

            if (reasonList.length == 0) {
                layer.msg("请选择退款缘由！");
                return false;
            }

            var params = normalizeParams(formData);
            params.reasonList = reasonList;
            params.companyName = $('#companyId option:selected').text();
            params.masterName = $('#masterId option:selected').text();

            // 退款金额必须大于0
            if (params.refundAmount <= 0) {
                layer.msg("金额不能为空或0");
                return false;
            }

            // 保存
            saveRefund(params, obj.elem);
            return false;
        });

        // 服务商师傅联动
        form.on('select(companyId)', function(data){
            let params = {
                manageCompanyId: data.value,
                plat: plat
            };

            $http.get(MASTER_LIST_URL, params).then(function (data) {
                renderMasterSelect(data)
            }, function (msg) {
                layer.msg(msg);
            });
        });

        // 退款路径
        form.on('radio(payTargetChannelId)', function(data){
            chageRefundPathOpenHtml(data.value);
        });

        // 退款方式
        form.on('radio(refundType)', function(data){
            changeRefundType(data.value)
        });

        // 监听 退款金额变化
        $('#online_amount').on('change', function(){
            var val = $(this).val();
            if(val > 1000000 || val < 0){
                layer.msg("范围在0-1000000之间");
                $("#online_amount").val("");
            }
            if(!isNumber(val)){
                layer.msg("请输入最多两位小数");
                $("#online_amount").val("");
            }
            if(NP.times(val, 100) > maxBacktrackingAmount){
                layer.msg("总计退款金额超过最大可以原路退金额");
                $("#online_amount").val("");
            }
        });

        $('#offline_amount').on('change', function(){
            var val = $(this).val();
            if(val > 1000000 || val < 0){
                layer.msg("范围在0-1000000之间");
                $("#offline_amount").val("");
            }
            if(!isNumber(val)){
                layer.msg("请输入最多两位小数");
                $("#offline_amount").val("");
            }
            if(NP.times(val, 100) > maxRefundAmount){
                layer.msg("总计退款金额超过原单金额");
                $("#offline_amount").val("");
            }
        });


    }


    // 程序入口
    function init () {
       // 初始化页面
       initPage();
       // 初始化事件
       initEvent();
    }
    // 初始化
    init();

    exports('oms_work_modify_refund');
});
